package controllers;

import java.util.List;

import models.Answer;
import models.Comment;
import models.Question;
import models.User;
import play.data.validation.Email;
import play.data.validation.Equals;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.libs.Codec;
import play.mvc.*;

@With(Secure.class)
public class Users extends Controller {

    public static void index() {
    	List<User> users = User.find("isAdmin = false order by name asc").fetch();
        render(users);
    }
    
    public static void show(Long userId) {
    	User user = User.findById(userId);
    	
    	if(user != null && !user.isAdmin)
    		render(user, null, null, null);
    	else
    		Application.index();
    }
    
    public static void findPosts(Long userId) {
    	User user = User.findById(userId);
    	
    	List<Question> questions = user.findAllQuestions();
    	List<Answer> answers = user.findAllAnswers();
    	List<Comment> comments = user.findAllComments();
    	
    	flash.put("results", "results");
    	
    	renderTemplate("Users/show.html", user, questions, answers, comments);
    }
    
    public static void edit() {
    	User user = Security.getConnected();
    	
    	render(user);
    }
    
    public static void saveChanges(@Email String email, 
			String realname, 
			@MinSize(5) String password, 
			@Equals("password") String passwordRepeat) {
    	
    	User user = Security.getConnected();
    	
    	if (validation.hasErrors() || !User.isEmailAvailable(email)) {
    		if (!User.isEmailAvailable(email))
        		flash.put("mailError", "Sorry, but this adress is already in use.");
    		
            validation.keep();
            params.flash();
            flash.error("Please correct these errors !");
            edit();
        }
    	
    	if(email.length() > 0)
    		user.email = email;
    	
    	if(realname.length() > 0)
    		user.realname = realname;
    	
    	if(password.length() > 0)
    		user.passwordHash = Codec.hexMD5(password);
    	
    	user.save();
    	
    	flash.success("Changes saved");
    	
    	show(user.id);
    }

}
